<template>
	<view class="order-pages" :style="{background:pageColor,overflowY:scrollEnabled?'hidden':'auto'}">
		<!-- #ifdef H5 -->
		<view @tap="$util.goUrl({url:`/pages/service`,openType:`reLaunch`})" class="abs"
			:class="[{'back-user-ios none': configInfo.isIos},{'back-user-android none': !configInfo.isIos}]"
			style="z-index: 999;" :style="{background:'rgba(255,255,255,0.5)'}" v-if="options.paysuc">
			<view class="iconshouye iconfont"></view>
			<view class="back-user_text">回到首页</view>
		</view>
		<!-- #endif -->
		<!-- #ifndef H5 -->
		<uni-nav-bar :fixed="true" :shadow="false" :statusBar="true" title="三方订单详情" color="#333"
			:backgroundColor="pageScrollTop>0?primaryColor:'none'" leftIcon="icon-left">
		</uni-nav-bar>
		<view :style="{height:`${configInfo.navBarHeight}px`}"></view>
		<!-- #endif -->
		<abnor v-if="detail == 405" :isCenter="true" :tip="[{text: '订单已拒单'}]">
		</abnor>
		<view v-if="detail.id">
			<view class="nav-bg">
				<image src="https://api.huixuananmm.com/admin/anmo/order/nav-bg.png" mode="aspectFill"></image>
			</view>
			<view class="rel">
				<!-- // pay_type 1待支付，2待服务，3技-师接单，4技-师出发，5技-师到达，6服务中，7已完成 -->
				<view class="item-child pl-lg pr-lg pt-lg f-paragraph c-paragraph">
					<view style="height:60rpx" v-if="options.paysuc"></view>
					<view class="flex-y-baseline">
						<view class="flex-center" @tap="$refs.order_type_box.open()">
							<view class="text-bold c-title f-md-title pr-sm">{{statusType[detail.pay_type]}}</view>
							<view class="flex-center fill-base pay-type-icon">
								<i class="iconfont iconchefeijifeiguize c-caption"
									style="font-size: 12px;line-height: normal;"></i>
							</view>
						</view>
					</view>
				</view>

				<view class="abnormal-order-info flex-center mt-md ml-lg mr-lg f-desc"
					@tap.stop="$util.goUrl({url:`/technician/pages/order/abnormal?id=${detail.abn_order_id}`})"
					v-if="detail.abn_order_id">
					<i class="iconfont iconyichangdingdan mr-sm"></i>
					<view class="flex-1 flex-between">
						此单被平台标记为异常
						<view class="flex-y-baseline">查看<i class="iconfont icon-right text-bold"></i></view>
					</view>
				</view>

				<view class="pd-md mt-md ml-lg mr-lg fill-base f-desc radius-16"
					v-if="detail.pay_type == 6 && !detail.is_add">
					<view class="flex-y-center">
						服务还有<min-countdown :type="3" :color="primaryColor" :bgColor="rgbaColor"
							countdownClass="coach-order-detail" :targetTime="detail.start_service_time_unix*1000"
							@callback="countEnd"></min-countdown>
						<view class="ml-sm">结束</view>
					</view>
				</view>

				<view class="item-child mt-md ml-lg mr-lg pl-lg fill-base radius-16 flex-between"
					v-if="detail.sign_img">
					<text class="c-title">客户签字</text>
					<image @tap.stop="previewImage(detail.sign_img,[detail.sign_img])" class="sign_img radius-16"
						:src="detail.sign_img" mode="aspectFill">
					</image>
				</view>

				<view class="item-child mt-md ml-lg mr-lg pd-lg fill-base radius-16 ">
					<view class="pb-md f-paragraph c-title text-bold">服务内容</view>
					<view class="f-paragraph text-bold">{{detail.ser_name}}</view>
					<view class="flex-between pt-md">
						<view class="c-title f-paragraph">单价(元/小时)</view>
						<view class="c-title f-paragraph font-num">¥{{detail.ser_price}}</view>
					</view>
					<view class="flex-between pt-md">
						<view class="c-title f-paragraph">总价</view>
						<view class="c-title f-paragraph font-num">¥{{detail.ser_total_price}}</view>
					</view>
					<view class="flex-between pt-md">
						<view class="c-title f-paragraph">预估收益</view>
						<view class="f-paragraph c-warning font-num flex-y-baseline">
							<text class="f-caption" style="padding-right: 2px;">¥</text>
							<text class="text-bold">{{detail.ser_total_price}}</text>
						</view>
					</view>
				</view>

				<view class="store-info mt-md ml-lg mr-lg pd-lg  fill-base radius-16" v-if="detail.store_id">
					<view class="f-mini-title c-title text-bold pb-md">
						{{detail.store_info.title}}
					</view>
					<view class="flex-between">
						<view class="c-title flex-1 mr-md" style="color: #303030;">
							<span>{{detail.store_info.address || `暂未设置门店地址`}}</span>
							<span @tap.stop="toCopy(detail.store_info.address)">
								<span class="iconfont iconfuzhi pl-sm" style="margin-right: 6rpx;"
									:style="{color: primaryColor}"></span>
								<span class="f-desc" :style="{color:primaryColor}">复制</span>
							</span>
						</view>
						<view class="flex-center">
							<view @tap.stop="toConfirmTel(detail.store_info.phone)"
								class="item-icon rel flex-center radius-16" v-if="detail.store_info.phone">
								<view class="item-icon radius-16 abs" :style="{background:primaryColor}"></view>
								<i class="iconfont icondadianhua_1" :style="{color:primaryColor}"></i>
							</view>
							<view @tap.stop="toMap('store_info')" class="item-icon rel flex-center radius-16 ml-md"
								v-if="detail.store_info.address">
								<view class="item-icon radius-16 abs" :style="{background:primaryColor}"></view>
								<i class="iconfont icondizhi_1" :style="{color:primaryColor}"></i>
							</view>
						</view>
					</view>
				</view>

				<view class="mt-md ml-lg mr-lg pd-lg fill-base f-paragraph c-title radius-16">
					<view class="flex-between mt-md">
						<view>服务时长</view>
						<view>{{detail.time_long}}分钟</view>
					</view>
					<view class="flex-between mt-md">
						<view>服务时间</view>
						<view>{{detail.service_data_time}}</view>
					</view>
				</view>

				<view class="mt-md ml-lg mr-lg pd-lg fill-base f-paragraph c-title radius-16">
					<view class="flex-between">
						<view>下单人</view>
						<view class="c-title ellipsis max-350">
							{{detail.user_name}}
						</view>
					</view>
					<view class="flex-between mt-md">
						<view>联系方式</view>
						<view class="flex">
							<view>
								{{detail.phone.substring(0,3)}}****{{detail.phone.substring(7,11)}}
							</view>
							<view @tap="toTel" v-if="detail.pay_type != 2" class="flex-center radius-16 ml-md"
								style="width: 44rpx;height: 44rpx;" :style="{color:primaryColor,background:rgbaColor}">
								<i class="iconfont icondianhua3"></i>
							</view>
						</view>
					</view>
					<view class="mt-md flex-x-between" v-if="!detail.store_id">
						<view>服务地址</view>
						<view class="flex-center max-450">
							<view class="flex-1 c-title mr-md" style="line-height: 40rpx;">
								<span>{{`${detail.address}${detail.address_info}`}}</span>
								<span @tap.stop="toCopy(`${detail.address}${detail.address_info}`)">
									<span class="iconfont iconfuzhi pl-sm" style="margin-right: 6rpx;"
										:style="{color: primaryColor}"></span>
									<span class="f-desc" :style="{color:primaryColor}">复制</span>
								</span>
								<span @tap.stop="$util.goUrl({url:`/technician/pages/order/update-addr`})"
									:style="{color: primaryColor}"
									v-if="detail.coach_update_address_auth && [3,4,5].includes(detail.pay_type)">
									<span class="iconfont iconxiugai pl-md" style="margin-right: 6rpx;"></span>
									<span class="f-desc">修改</span>
								</span>
							</view>
							<view @tap="toMap('address_info')" class="flex-center radius-16"
								style="width: 44rpx;height: 44rpx;" :style="{color:primaryColor,background:rgbaColor}">
								<i class="iconfont icondizhi31"></i>
							</view>
						</view>
					</view>
					<view class="flex-between mt-md" v-if="detail.distance">
						<view>接单距离</view>
						<view class="c-title ellipsis max-350">
							{{detail.distance | hannelDistance}}
						</view>
					</view>
				</view>


				<view class="footer-info fix fill-base"
					v-if="statusPayType.includes(detail.pay_type) || (detail.pay_type == 7 && !detail.is_add)">
					<view class="flex-between pd-lg">
						<view></view>
						<view class="flex-center f-desc c-title">
							<!-- // pay_type 2待接单，5待服务，6服务中，7已完成 -->
							<block v-if="[3,4,5,6].includes(detail.pay_type)">
								<view @tap.stop="toTel" class="oper-btn flex-center f-mini-title"
									:style="{color:primaryColor,borderColor:primaryColor}">
									联系客户</view>
							</block>
							<!-- 待接单 -->
							<block v-if="detail.pay_type == 2">
								<view @tap.stop="toRefuse(0)" class="oper-btn flex-center f-mini-title c-title">拒单
								</view>
								<view @tap.stop="toConfirm(detail.is_add && detail.add_flow_path == 2?6:3)"
									class="oper-btn flex-center f-mini-title c-base"
									:style="{background:primaryColor,borderColor:primaryColor}">接单</view>
							</block>
							<!-- 待服务 -->
							<block v-if="[3,4,5].includes(detail.pay_type)">
								<view
									@tap.stop="toConfirm(detail.is_add || detail.store_id  ? 6 : detail.pay_type*1+1 )"
									class="oper-btn flex-center f-mini-title c-base"
									:style="{background:primaryColor,borderColor:primaryColor}"
									v-if="(detail.is_add && detail.add_flow_path == 1) || !detail.is_add">
									{{detail.is_add || detail.store_id ? '开始服务' : detail.pay_type == 3 ? '确认出发': detail.pay_type == 4 ?'拍照打卡' : '开始服务'}}
								</view>
							</block>
							<!-- 服务中 -->
							<block v-if="detail.pay_type == 6">
								<view @tap.stop="toConfirm(7)" class="oper-btn flex-center f-mini-title c-base"
									:style="{background:primaryColor,borderColor:primaryColor}"
									v-if="(detail.is_add && detail.add_flow_path == 1) || !detail.is_add">结束打卡</view>
							</block>
							<!-- 已完成 -->
							<block v-if="detail.pay_type == 7">
								<view @tap.stop="toChangeItem('del_item')"
									class="oper-btn flex-center f-mini-title c-title">删除订单
								</view>
								<!-- <view
									@tap.stop="$util.goUrl({url:`/technician/pages/order/label?id=${detail.id}&uid=${detail.user_id}`})"
									class="oper-btn flex-center f-mini-title c-base"
									:style="{background:primaryColor,borderColor:primaryColor}" v-if="!detail.label_time">
									评价客户</view> -->

							</block>
						</view>
					</view>
					<view class="space-safe"></view>
				</view>
			</view>
			<common-popup @confirm="confirmOperItem" ref="del_item" type="DELETE_ORDER"
				:info="popupInfo"></common-popup>

			<uni-popup ref="refuse_item" type="center" :custom="true">
				<view class="common-popup-content fill-base pd-lg radius-34">
					<view class="title">拒单</view>
					<view class="desc">请确认是否拒接接单</view>
					<textarea v-model="coach_refund_text" class="pd-lg textarea f-desc c-title mt-lg radius-20"
						maxlength="200" placeholder="请输入拒单原因" placeholder-class="f-desc c-caption"></textarea>
					<view class="flex-center mt-md" style="width: 540rpx">
						<view class="flex-1"></view>
						<view>{{coach_refund_text.length>200?200:coach_refund_text.length}}/200</view>
					</view>
					<view class="button">
						<view @tap.stop="$refs.refuse_item.close()" class="item-child">取消</view>
						<view @tap.stop="confirmRefuse" class="item-child c-base"
							:style="{background: primaryColor,color:'#fff'}">确定</view>
					</view>
				</view>
			</uni-popup>


			<uni-popup ref="oper_item" type="center" :custom="true">
				<view class="common-popup-content fill-base pd-lg radius-34">
					<view class="title">{{popupInfo.title}}</view>
					<view class="desc">
						温馨提示：定位需要5秒左右才能返回结果，<span style="color: #F13F26;">若打卡位置与您实际位置不符，请使用手动搜索位置获取定位</span>
					</view>
					<view class="space-sm"></view>
					<view class="flex-warp mt-md" style="width: 100%;" v-if="popupInfo.type !== 4">
						<view>拍照打卡：</view>
						<view class="flex-1">
							<upload @upload="imgUpload" @del="imgUpload" :imagelist="popupInfo.imgs" filetype="picture"
								imgtype="imgs" text="拍摄图片" :imgsize="1" :sourceType="2">
							</upload>
						</view>
					</view>
					<view class="flex-warp mt-md" style="width: 100%;" v-if="popupInfo.location">
						<view>当前地点：</view>
						<view class="flex-1"
							:class="[{'c-title':popupInfo.location.address},{'c-caption':!popupInfo.location.address}]">
							<span v-if="popupInfo.location.address">{{popupInfo.location.address}}</span>
							<span v-else>{{popupInfo.isLoca ? '定位失败，请选择手动定位':'定位中请耐心等待'}}</span>
							<span @tap.stop="toChooseLocation" class="c-warning ml-sm"
								v-if="popupInfo.isLoca">手动定位</span>
						</view>
					</view>
					<!-- #ifdef H5 -->
					<view @tap.stop="$refs.show_location_item.open()" class="flex-y-center f-paragraph mt-md"
						style="width:100%;color:#5a677e">
						定位失败或不准确时您可以这样操作<i class="iconfont iconwentifankui3 ml-sm" style="font-size:28rpx;"></i>
					</view>
					<!-- #endif -->
					<view class="button">
						<view @tap.stop="$refs.oper_item.close()" class="item-child">取消</view>
						<view @tap.stop="confirmOper" class="item-child c-base"
							:style="{background: primaryColor,color:'#fff'}">确定</view>
					</view>
				</view>
			</uni-popup>


			<longbingbing-location-fail ref="show_location_item"></longbingbing-location-fail>

			<uni-popup ref="balance_discount_item" type="bottom" :custom="true">
				<view class="common-popup-content fill-base pd-lg" style="width: 100%;border-radius: 34rpx 34rpx 0 0;"
					v-if="detail.pay_model==4">
					<view class="title">折扣明细</view>
					<scroll-view scroll-y @touchmove.stop.prevent class="balance-disocunt-list mt-lg">
						<view class="mt-md" v-for="(item,index) in detail.balance_discount_list" :key="index">
							<view class="f-mini-title c-title text-bold">{{item.title}} ({{item.discount}}折)</view>
							<view class="flex-center f-paragraph c-title mt-sm">
								<view class="list-item">消费 ¥{{item.value_cash}}</view>
								<view class="list-item">抵扣 ¥{{item.cash}}</view>
								<view class="list-item">优惠 ¥{{item.discount_cash}}</view>
							</view>
						</view>
					</scroll-view>
					<view class="flex-between f-paragraph c-title b-1px-t mt-lg pt-lg" style="width:100%">
						<view>共优惠</view>
						<view class="f-mini-title text-bold c-warning">¥{{detail.balance_discount_cash}}</view>
					</view>
					<view class="button">
						<view @tap.stop="$refs.balance_discount_item.close()" class="item-child"
							:style="{background: primaryColor,color:'#fff'}">知道了</view>
					</view>
					<view class="space-safe"></view>
				</view>
			</uni-popup>


			<uni-popup ref="order_type_box" type="center" :custom="true">
				<div class="fill-base order-type-box pt-lg">
					<view class="pb-lg f-title text-bold flex-center rel">
						订单流程
						<view class="abs" style="top:0;right: 30rpx;" @tap="$refs.order_type_box.close()">
							<i class="iconfont iconguanbi1" style="color:#6A6A6A;font-size: 28rpx;"></i>
						</view>
					</view>
					<scroll-view scroll-y class="mt-md" style="width: 100%;max-height:50vh">
						<view class="pl-lg pr-lg pb-lg">
							<timeline :list="lineList" :info="detail" type="coach"></timeline>
						</view>
					</scroll-view>
					<view class="space-safe"></view>
				</div>
			</uni-popup>


			<!-- #ifdef H5 -->
			<block v-if="configInfo.plugAuth.recording && configInfo.service_recording_show && pageLen == 1">
				<media-recorder ref="recorder" @success='handlerSuccess' @save="handlerOnSave"
					@error='handlerError'></media-recorder>
			</block>
			<!-- #endif -->


			<!-- #ifdef MP-WEIXIN -->
			<user-privacy ref="user_privacy" :show="false"></user-privacy>
			<!-- #endif -->
			<!-- #ifdef APP-PLUS -->
			<longbingbing-preview-image ref="preview_image_item"></longbingbing-preview-image>
			<longbingbing-app-check-auth type="phone" ref="app_check_item"
				@confirm="$util.goUrl({ url:call_phone, openType: 'call' })"></longbingbing-app-check-auth>
			<!-- #endif -->
		</view>
	</view>
</template>
<script>
	import {
		mapState,
		mapActions,
		mapMutations
	} from "vuex"
	import timeline from '@/components/timeline.vue'
	import orderMap from '@/components/order-map.vue'
	import longbingbingLocationFail from "@/components/longbingbing-location-fail.vue"
	// #ifdef H5
	import MediaRecorder from '@/components/media-recorder.vue'
	// #endif
	// #ifndef H5
	var recorderManager = null;
	// #endif
	export default {
		components: {
			timeline,
			orderMap,
			longbingbingLocationFail
			// #ifdef H5
			,
			MediaRecorder
			// #endif
		},
		data() {
			return {
				options: {},
				call_phone: '',
				statusPayType: [2, 3, 4, 5, 6],
				statusType: {
					'-1': '已取消',
					2: '待接单',
					3: '已接单',
					4: '已出发',
					5: '已到达',
					6: '服务中',
					7: '已完成',
					8: '待转单'
				},
				carType: {
					0: '公交/地铁',
					1: '出租车'
				},
				payType: {
					1: '微信支付',
					2: '余额支付',
					3: '支付宝支付',
					4: '折扣卡支付'
				},
				lineList: [],
				base_service: [{
					pay_type: 3,
					title: this.$t('action.attendantName') + '接单',
					time: 'receiving_time',
					icon: 'iconjishijiedan'
				}, {
					pay_type: 4,
					title: this.$t('action.attendantName') + '出发',
					time: 'serout_time',
					addr: 'serout_address',
					icon: 'iconjishichufa'
				}, {
					pay_type: 5,
					title: this.$t('action.attendantName') + '到达',
					time: 'arrive_time',
					img: 'arrive_img',
					addr: 'arr_address',
					icon: 'iconjishidaoda'
				}, {
					pay_type: 6,
					title: '开始服务',
					time: 'start_service_time',
					icon: 'iconjishifuwu'
				}, {
					pay_type: 7,
					title: '服务完成',
					time: 'order_end_time',
					img: 'end_img',
					addr: 'end_address',
					icon: 'iconjishiwancheng'
				}],
				base_bell: [{
					pay_type: 3,
					title: this.$t('action.attendantName') + '接单',
					time: 'receiving_time',
					icon: 'iconjishijiedan'
				}, {
					pay_type: 6,
					title: '开始服务',
					time: 'start_service_time',
					icon: 'iconjishifuwu'
				}, {
					pay_type: 7,
					title: '服务完成',
					time: 'order_end_time',
					img: 'end_img',
					addr: 'end_address',
					icon: 'iconjishiwancheng'
				}],
				pageScrollTop: 0,
				rgbaColor: '',
				detail: {
					pay_type: 0
				},
				oper_add_id: 0,
				check_label: [],
				coach_refund_text: '',
				lockTap: false,
				popupInfo: {
					title: '',
					type: '',
					param: {},
					imgs: [],
					isLoca: false,
					location: {
						lat: 0,
						lng: 0,
						address: ''
					}
				},
				pageLen: 1,
				// #ifndef H5
				isReset: false,
				duration_time: 600,
				// #endif
			}
		},
		computed: mapState({
			configInfo: state => state.config.configInfo,
			isUserMedia: state => state.order.isUserMedia,
			recorder: state => state.order.recorder,
			recorder_status: state => state.order.recorder_status,
			recorder_order_id: state => state.order.recorder_order_id,
			order_unix_list: state => state.order.order_unix_list,
			over_time_text() {
				return new Date().getTime() + this.detail.over_time * 1000
			}
		}),
		onLoad(options) {
			let {
				id = 0
			} = options
			options.id = id * 1
			this.options = options
			this.initIndex()
		},
		onPageScroll(e) {
			let {
				scrollTop
			} = e
			this.pageScrollTop = scrollTop
		},
		methods: {
			...mapActions(['getConfigInfo', 'toPlayAudio']),
			...mapMutations(['updateUserItem', 'updateOrderItem']),
			async initIndex(refresh = false) {
				if (!this.configInfo.id || refresh || !this.userInfo.id) {
					await this.getConfigInfo()
				}
				this.rgbaColor = this.$util.rgbColor(this.primaryColor, 0.15)
				let {
					id
				} = this.options
				let data = await this.$api.technician.dispatchOrderInfo({
					order_id: id
				})
				this.$util.setNavigationBarColor({
					color: '#000000',
					bg: this.primaryColor
				})
				if (data == 405) {
					this.detail = data
					return
				}
				data.service_data_time = this.$util.formatTime(data.start_time * 1000, 'YY-M-D h:m') + ' - ' + this
					.$util.formatTime(data.end_time * 1000, 'h:m')
				if (this.$util.formatTime(data.start_time * 1000, 'h:m') > this.$util.formatTime(data.end_time * 1000,
						'h:m')) {
					data.service_data_time = this.$util.formatTime(data.start_time * 1000, 'YY-M-D h:m') + ' - ' + this
						.$util.formatTime(data.end_time * 1000, 'M-D h:m')
				}
				data.receiving_time = data.receiving_time ? this.$util.formatTime(data.receiving_time * 1000) : 0
				data.start_service_time = data.start_service_time ? this.$util.formatTime(data.start_service_time *
					1000) : 0
				data.serout_time = data.serout_time ? this.$util.formatTime(data.serout_time * 1000) : 0
				data.arrive_time = data.arrive_time ? this.$util.formatTime(data.arrive_time * 1000) : 0
				data.order_end_time = data.order_end_time ? this.$util.formatTime(data.order_end_time * 1000) : 0
				data.map_type = ''

				data.is_balance = data.balance * 1 > 0 ? 1 : 0
				data.start_service_time_unix = ''
				let {
					pay_type,
					total_time_long: time_long,
					receiving_time = '',
					start_service_time = '',
					is_add = 0,
					store_id = 0,
					add_flow_path = 1,
				} = data
				if (is_add) {
					if (!receiving_time && pay_type > 3) {
						data.receiving_time = start_service_time
					}
					if (!start_service_time && pay_type > 5) {
						data.start_service_time = receiving_time
					}
				}
				if (pay_type > 5 && !is_add) {
					let {
						order_unix_list
					} = this
					if (pay_type == 6) {
						let start_service_time_unix = this.$util.DateToUnix(start_service_time) + time_long * 60
						data.start_service_time_unix = start_service_time_unix
						let unix_items = {
							id,
							time_long,
							start_service_time,
							start_service_time_unix
						}
						let unixInd = order_unix_list.findIndex(item => {
							return item.id === id
						})
						if (unixInd != -1) {
							order_unix_list[unixInd] = unix_items
						} else {
							order_unix_list.push(unix_items)
						}
						this.updateOrderItem({
							key: 'order_unix_list',
							val: order_unix_list
						})
					} else {
						let unix_list = order_unix_list.filter(aitem => {
							return aitem.id != id
						})
						if (unix_list.length !== order_unix_list.length) {
							this.updateOrderItem({
								key: 'order_unix_list',
								val: unix_list
							})
						}
					}
				}
				let lineList = this.$util.deepCopy(is_add || store_id ? this.base_bell : this.base_service)
				let ind = lineList.findIndex(item => {
					return item.title == '签字确认'
				})
				if (store_id && ind == -1) {
					lineList.push({
						pay_type: 7,
						title: '签字确认',
						time: 'sign_time',
						icon: ''
					})
				}
				this.lineList = lineList
				this.detail = data

				let pageLen = getCurrentPages().length
				this.pageLen = pageLen

				// #ifndef H5
				if (!refresh && pageLen == 1) {
					recorderManager = uni.getRecorderManager()
					//开始录音
					recorderManager.onStart(() => {
						this.$util.log('开始录音')
					})
					//结束录音
					recorderManager.onStop((res) => {
						this.$util.log('结束录音', res)
						this.handlerOnSave(res)
						let {
							duration
						} = res
						let currentTime = parseInt(duration / 1000)
						let isReset = this.duration_time * 1 - currentTime > 1 ? false : true
						this.isReset = isReset
						if (isReset) {
							this.handlerOnChanger()
						}
					})
					// 录音异常
					recorderManager.onError((e) => {
						this.$util.log('录音异常', e)
					})
				}
				// #endif

				// #ifdef H5
				if (!refresh) {
					let {
						status: coach_status = 0,
						coach_position = 0
					} = this.userCoachStatus
					if (coach_position && coach_status == 2) {
						this.$util.getCoachUtilLoca()
						this.$jweixin.hideOptionMenu()
					} else {
						this.$jweixin.initJssdk(() => {
							this.$jweixin.hideOptionMenu()
						})
					}
				}
				// #endif
			},
			async initRefresh() {
				await this.initIndex(true)
			},
			countEnd() {
				this.$util.log("倒计时完了")
				setTimeout(() => {
					this.toCountDownEnd()
				}, 1000)
			},
			// 开始录音
			async handlerOnChanger() {
				// #ifdef MP-WEIXIN
				let privacyCheck = this.$refs.user_privacy.check()
				if (privacyCheck) {
					this.$refs.user_privacy.open()
					return
				}
				// #endif
				// #ifndef H5
				await this.$util.checkAuth({
					type: "record"
				});
				// #endif
				let {
					recorder_status,
					duration_time
				} = this
				if (recorder_status) {
					// #ifdef H5
					this.$refs.recorder.stop()
					// #endif
					// #ifndef H5
					recorderManager.stop()
					// #endif
				} else {
					// #ifdef H5
					this.$refs.recorder.start()
					// #endif
					// #ifndef H5
					recorderManager.start({
						format: 'mp3',
						duration: duration_time * 1000,
					})
					// #endif
				}
				this.updateOrderItem({
					key: 'recorder_status',
					val: !recorder_status
				})
			},
			async handlerOnEnd() {
				// #ifdef H5
				this.$refs.recorder.stop()
				setTimeout(() => {
					this.handlerOnSave()
				}, 1000)
				// #endif
				// #ifndef H5
				recorderManager.stop()
				// #endif
				this.updateOrderItem({
					key: 'recorder_status',
					val: false
				})
			},
			async handlerOnSave(res = {}) {
				this.$util.showLoading({
					title: `录音上传中`
				})
				let filePath = ''
				// #ifdef H5
				let unix = parseInt(new Date().getTime() / 1000)
				let name = `服务过程录音-${unix}.mp3`
				let {
					data
				} = this.recorder
				let file = new File([data], name, {
					type: 'audio/mp3'
				})
				filePath = URL.createObjectURL(file)
				// #endif
				// #ifndef H5
				let {
					tempFilePath,
				} = res
				filePath = tempFilePath
				// #endif

				let {
					attachment_path: link
				} = await this.$api.base.uploadFile({
					filePath,
					formData: {
						type: 'audio'
							// #ifdef H5
							,
						name
						// #endif
					}
				})
				let {
					recorder_order_id: order_id
				} = this
				await this.$api.technician.recordingAdd({
					order_id,
					link
				})
				this.$util.hideAll()
			},
			// #ifdef H5
			handlerSuccess(res) {
				this.updateOrderItem({
					key: 'recorder',
					val: res
				})
			},
			handlerError(code) {
				switch (code) {
					case '101':
						uni.showModal({
							content: '当前浏览器版本较低，请更换浏览器使用，推荐在微信中打开。'
						})
						break;
					case '201':
						uni.showModal({
							content: '麦克风权限被拒绝，请刷新页面后授权麦克风权限。'
						})
						break
					default:
						uni.showModal({
							content: '未知错误，请刷新页面重试'
						})
						break
				}
			},
			// #endif 
			// 服务倒计时结束
			async toCountDownEnd() {
				await this.initRefresh()
				this.$util.back()
				let {
					recorder_status,
					recorder_order_id,
					pageLen
				} = this
				let {
					id,
					total_time_long: time_long,
					start_service_time = ''
				} = this.detail
				let unix = Math.ceil(((this.$util.DateToUnix(start_service_time) + time_long * 60) * 1000 -
					new Date().getTime()) / 1000)
				if (recorder_order_id == id && recorder_status && unix < 1) {
					if (pageLen == 1) {
						await this.handlerOnEnd()
						// #ifdef H5
						this.$refs.recorder.clear()
						// #endif
					} else {
						await this.$util.getPage(-1).handlerOnEnd()
						await this.$util.getPage(-1).$refs.recorder.clear()
					}
				}
			},
			async toLabel() {
				let {
					user_id
				} = this.detail
				this.$util.goUrl({
					url: `/technician/pages/order/user-label?id=${user_id}`
				})
			},
			// 操作加钟订单
			async toChangeAddOrderItem(index) {
				let {
					add_order_id,
					add_flow_path = 1
				} = this.detail
				let {
					id,
					pay_type,
				} = add_order_id[index]

				if ((add_flow_path == 2 && pay_type > 2) || (add_flow_path == 1 && pay_type > 6)) {
					this.$util.goUrl({
						url: `/technician/pages/order/detail?id=${id}`
					})
					return
				}
				if (pay_type == 2 || (add_flow_path == 1 && [3, 6].includes(pay_type))) {
					this.toConfirm(pay_type == 2 ? add_flow_path == 1 ? 3 : 6 : pay_type == 3 ? 6 : 7, id)
				}
			},
			// 拒绝接单
			async toRefuse(id = 0) {
				// this.oper_add_id = id
				// this.coach_refund_text = ''
				// this.$refs.refuse_item.open()
				this.toConfirm(-1, id)
			},
			// 确认：拒绝接单
			async confirmRefuse() {
				let {
					oper_add_id,
					coach_refund_text = ''
				} = this
				coach_refund_text = coach_refund_text.length > 0 ? coach_refund_text.replace(
					/(^\s*)|(\s*$)/g, "") : ''
				if (coach_refund_text.length == 0) {
					this.$util.showToast({
						title: `请输入拒单原因`
					})
					return
				}
				this.coach_refund_text = this.coach_refund_text.substring(0, 200)
				this.toConfirm(-1, oper_add_id)
			},
			// 获取定位
			async toGetLocation() {
				this.popupInfo.isLoca = false
				this.popupInfo.location = {
					isIp: false,
					lat: 0,
					lng: 0,
					address: ''
				}
				this.$util.showLoading({
					title: '定位中'
				})
				try {
					let {
						lat,
						lng
					} = await this.$util.getCoachUtilLoca(false)
					this.initUtilLocaData(lat, lng, false)
				} catch (e) {
					console.log(e, "=====catch e")
					let {
						lat,
						lng
					} = await this.$util.getLocation()
					this.initUtilLocaData(lat, lng, false)
				}
			},
			async initUtilLocaData(lat, lng, isIp) {
				if (!lat && !lng) {
					this.popupInfo.isLoca = true
					this.$util.hideAll()
					return
				}
				let {
					address
				} = await this.$util.getMapAddr({
					lat,
					lng
				})
				let location = {
					lat,
					lng,
					address
				}
				if (!isIp) {
					this.$util.updateCoachAddr(location)
				}
				let data = Object.assign({}, this.popupInfo, {
					isLoca: true,
					location
				})
				this.$nextTick(() => {
					this.popupInfo = data
				})
				this.$util.hideAll()
			},
			imgUpload(e) {
				let {
					imagelist,
					imgtype
				} = e;
				this.popupInfo[imgtype] = imagelist;
			},
			// 选择地区
			async toChooseLocation() {
				// #ifdef APP-PLUS
				this.$util.goUrl({
					url: `/user/pages/choose/addr?from=order`
				})
				// #endif
				// #ifndef APP-PLUS
				this.toConfirmChooseLoca()
				// #endif
			},
			async toConfirmChooseLoca() {
				// #ifdef MP-WEIXIN
				let privacyCheck = this.$refs.user_privacy.check()
				if (privacyCheck) {
					this.$refs.user_privacy.open()
					return
				}
				// #endif 

				let {
					lat,
					lng,
					address,
					name
				} = await this.$util.chooseLocation()
				if (!lat && !lng) return
				if (name && !address) {
					this.$util.showToast({
						title: `请选择具体的地址`
					})
					return
				}
				this.popupInfo.location = {
					map_type: 1,
					isIp: false,
					lat,
					lng,
					address: `${address} ${name}`
				}
			},
			// 确认： 4已出发/5已到达/7已完成
			async confirmOper() {
				let popupInfo = this.$util.deepCopy(this.popupInfo)
				let {
					type,
					param,
					imgs,
					location,
				} = popupInfo
				let {
					lat = 0, lng = 0
				} = location
				if ([5, 7].includes(type) && imgs.length === 0) {
					this.$util.showToast({
						title: `请先拍照`
					})
					return
				}
				if (!lat && !lng) {
					this.toGetLocation()
					return
				}
				if ([5, 7].includes(type)) {
					let {
						path
					} = imgs[0]
					location.path = path
				}
				this.toConfirmUpdate(type, param, location)
			},
			// type: -1拒绝接单，3确定接单，4已出发，5已到达，6开始服务，7完成服务
			async toConfirm(type, oper_add = 0) {
				if (this.lockTap) return

				let {
					id: order_id,
				} = this.detail
				if (oper_add) {
					order_id = oper_add
				}
				let param = {
					order_id,
					oper_add,
					type
				}
				if (type == -1) {
					param.coach_refund_text = this.coach_refund_text
				}

				if ([4, 5, 7].includes(type)) {
					let arr = {
						4: '确认出发',
						5: '拍照打卡',
						7: '结束打卡',
					}
					let title = arr[type]
					this.popupInfo = Object.assign({}, this.popupInfo, {
						title,
						type,
						param,
						imgs: [],
						isLoca: false,
						location: {
							lat: 0,
							lng: 0,
							address: ''
						}
					})
					this.$refs.oper_item.open()
					this.toGetLocation()
				} else {
					this.toConfirmUpdate(type, param)
				}
			},
			async toConfirmUpdate(type, param, location = {}) {
				if ([4, 5, 7].includes(type)) {
					let {
						lat,
						lng,
						address,
						path,
						map_type = 0
					} = location
					param.map_type = map_type
					if (type === 4) {
						param.serout_lat = lat
						param.serout_lng = lng
						param.serout_address = address
					}
					if (type == 5) {
						param.arrive_img = path
						param.arr_lat = lat
						param.arr_lng = lng
						param.arr_address = address
					}
					if (type == 7) {
						param.end_img = path
						param.end_lat = lat
						param.end_lng = lng
						param.end_address = address
					}
				}
				let msg = {
					'-1': '已拒绝接单',
					3: '接单成功',
					4: '已成功出发',
					5: '已成功到达',
					6: '已开始服务',
					7: '服务已完成'
				}

				if (this.lockTap) return
				this.lockTap = true


				let {
					plugAuth,
					service_recording_show
				} = this.configInfo
				let {
					recording
				} = plugAuth

				let {
					isUserMedia,
					recorder_order_id,
					recorder_status,
					pageLen
				} = this

				// #ifndef H5
				isUserMedia = 1
				// #endif

				let flag = true

				let {
					order_id,
					oper_add = 0
				} = param
				delete param.oper_add

				let {
					is_add,
				} = this.detail

				let order_info = {}
				try {
					order_info = await this.$api.technician.dispatchOrderInfo({
						order_id
					})
				} catch (e) {
					if (type == -1) {
						this.$refs.refuse_item.close()
					}
					if ([4, 5, 7].includes(type)) {
						this.$refs.oper_item.close()
					}
					this.$util.back()
					this.lockTap = false
					this.$util.hideAll()
					setTimeout(() => {
						this.$util.goUrl({
							url: 1,
							openType: `navigateBack`
						})
					}, 2000)
					return
				}

				let {
					pay_type
				} = order_info

				if (pay_type == 7 && recorder_order_id == this.detail.order_id && recorder_status) {
					if (pageLen == 1) {
						await this.handlerOnEnd()
						// #ifdef H5
						this.$refs.recorder.clear()
						// #endif
					} else {
						await this.$util.getPage(-1).handlerOnEnd()
						await this.$util.getPage(-1).$refs.recorder.clear()
					}
					this.updateOrderItem({
						key: 'haveOperItem',
						val: true
					})
				}

				is_add = !is_add ? oper_add : is_add

				if (!is_add && pay_type < type && type === 6 && recorder_order_id != order_id &&
					recorder_status) {
					let [res_del, {
						confirm
					}] = await uni.showModal({
						title: '提示',
						content: "已有开始的服务还未结束录音，请确认是否完成录音并开始新的服务？"
					})
					if (confirm) {
						if (pageLen == 1) {
							await this.handlerOnEnd()
							// #ifdef H5
							this.$refs.recorder.clear()
							// #endif
						} else {
							await this.$util.getPage(-1).handlerOnEnd()
							await this.$util.getPage(-1).$refs.recorder.clear()
						}
					} else {
						flag = false
					}
				}

				this.$util.showLoading()

				if (!flag) {
					this.lockTap = false
					this.$util.hideAll()
					return
				}

				try {
					if (type == -1) {
						this.$refs.refuse_item.close()
					}
					if ([4, 5, 7].includes(type)) {
						this.$refs.oper_item.close()
					}
					await this.$api.technician.dispatchUpdateOrder(param)
					if (type == 6) {
						if (!is_add) {
							this.toPlayAudio({
								key: 'service_start_recording'
							})
							if (isUserMedia && recording && service_recording_show) {
								let recordMsg = pageLen == 1 ? '若录音中退出页面将不会记录录音的音频！' : ''
								this.$util.hideAll()
								await uni.showModal({
									title: '提示',
									content: `服务过程将自动录音，直至服务结束！${recordMsg}`,
									showCancel: false,
									confirmText: '知道了'
								})
								this.updateOrderItem({
									key: 'recorder_order_id',
									val: order_id
								})
								if (pageLen == 1) {
									await this.handlerOnChanger()
								} else {
									await this.$util.getPage(-1).handlerOnChanger()
								}
							}
						}
						if (this.detail.is_add && pageLen > 1 && this.$util.getPage(-1).detail) {
							this.$util.getPage(-1).detail = {}
						}
						if (!this.detail.is_add) {
							this.detail = {}
						}
					}
					if (type == 7) {
						if (!is_add && recorder_order_id == order_id && recorder_status) {
							if (pageLen == 1) {
								await this.handlerOnEnd()
								// #ifdef H5
								this.$refs.recorder.clear()
								// #endif
							} else {
								await this.$util.getPage(-1).handlerOnEnd()
								await this.$util.getPage(-1).$refs.recorder.clear()
							}
						}
					}
					this.$util.hideAll()
					this.$util.showToast({
						title: msg[type]
					})
					if (type == -1) {
						this.$util.back()
						this.lockTap = false
						this.detail = 405
						return
					}
					await this.initRefresh()
					this.updateOrderItem({
						key: 'haveOperItem',
						val: true
					})
					setTimeout(() => {
						this.$util.back()
						this.lockTap = false
					}, 500)
				} catch (e) {
					this.updateOrderItem({
						key: 'haveOperItem',
						val: true
					})
					setTimeout(() => {
						this.initRefresh()
						this.$util.back()
						this.lockTap = false
						this.$util.hideAll()
					}, 2000)
				}
			},
			// 删除订单
			async toChangeItem(refs_key) {
				if (this.lockTap) return
				let {
					id,
					order_code,
					order_goods,
				} = this.detail
				// let {
				// 	goods_cover: image,
				// } = order_goods[0]
				this.popupInfo = {
					id,
					name: `单号：${order_code}`,
					image: '',
					refs_key
				}
				this.$refs[refs_key].open()
			},
			// 确认：删除订单
			async confirmOperItem() {
				let {
					id,
					index,
					refs_key,
				} = this.popupInfo
				let methodArr = {
					'del_item': ['dispatchDelOrder', '删除成功', -1]
				}
				let methodModel = methodArr[refs_key][0]
				let title = methodArr[refs_key][1]
				if (this.lockTap) return
				this.lockTap = true
				try {
					this.$refs[refs_key].close()
					await this.$api.technician[methodModel]({
						id
					})
					this.$util.showToast({
						title
					})
					setTimeout(() => {
						this.$util.back()
						this.$util.goUrl({
							url: 1,
							openType: `navigateBack`
						})
						this.lockTap = false
					}, 1000)
				} catch (e) {
					setTimeout(() => {
						this.lockTap = false
					}, 2000)
				}
			},
			// 咨询
			async toTel() {
				let {
					id: order_id,
					pay_type
				} = this.detail
				if ([3, 4, 5, 6].includes(pay_type)) {
					let url = await this.$api.technician.dispatchGetVirtualPhone({
						order_id
					})
					if (!url) {
						this.$util.showToast({
							title: `稍后会有电话打入，请注意接听哦`
						})
						return
					}
					// #ifdef APP-PLUS
					this.toConfirmTel(url)
					// #endif
					// #ifndef APP-PLUS
					this.$util.goUrl({
						url,
						openType: 'call'
					})
					// #endif
				} else {
					let msg = pay_type == 7 ? '服务结束' : '服务取消'
					this.$util.showToast({
						title: `${msg}不能联系客户哦`
					})
				}
			},
			toConfirmTel(url) {
				// #ifdef APP-PLUS
				if (plus.os.name == 'Android' && plus.navigator.checkPermission(
						'android.permission.CALL_PHONE') ===
					'undetermined') {
					this.call_phone = url
					this.$refs.app_check_item.open()
				} else {
					this.$util.goUrl({
						url,
						openType: 'call'
					})
				}
				// #endif
				// #ifndef APP-PLUS
				this.$util.goUrl({
					url,
					openType: 'call'
				})
				// #endif
			},
			// 查看定位
			async toMap(key) {
				// #ifdef MP-WEIXIN
				let privacyCheck = this.$refs.user_privacy.check()
				if (privacyCheck) {
					this.$refs.user_privacy.open()
					return
				}
				// #endif
				let {
					address,
					address_info = '',
					lat,
					lng
				} = this.detail
				// #ifdef APP-PLUS
				this.$util.goMap({
					lat,
					lng,
					address,
					address_info
				})
				return
				// #endif
				await this.$util.checkAuth({
					type: 'userLocation'
				})
				await uni.getLocation({
					type: 'gcj02',
				})
				await uni.openLocation({
					latitude: lat * 1,
					longitude: lng * 1,
					name: address_info ? `${address} ${address_info}` : address,
					scale: 28
				})
			},
			toCopy(url) {
				// #ifdef MP-WEIXIN
				let privacyCheck = this.$refs.user_privacy.check()
				if (privacyCheck) {
					this.$refs.user_privacy.open()
					return
				}
				// #endif
				this.$util.goUrl({
					url,
					openType: 'copy'
				})
			},
			previewImage(current, urls) {
				// #ifdef APP-PLUS 
				if (plus.os.name == 'Android' && plus.navigator.checkPermission(
						'android.permission.WRITE_EXTERNAL_STORAGE') === 'undetermined') {
					this.$refs.preview_image_item
						.previewImage({
							current,
							urls
						})
				} else {
					this.$util.previewImage({
						current,
						urls
					})
				}
				// #endif
				// #ifndef APP-PLUS
				this.$util.previewImage({
					current,
					urls
				})
				// #endif
			},
		},
		filters: {
			handlePayOrder(num) {
				return num === 1 ? '（首次下单）' : `（第${num}次下单）`
			},
			hannelDistance(val) {
				return (val / 1000).toFixed(2) + 'km'
			}
		}
	}
</script>


<style lang="scss">
	.order-pages {

		.call-btn {
			width: 128rpx;
			height: 49rpx;
			border-radius: 8rpx
		}

		.nav-bg {
			width: 100%;
			height: 500rpx;
			left: 0;
			// #ifndef H5
			top: 0;
			// #endif
			// #ifdef H5
			top: -88px;
			// #endif
			background-image: linear-gradient(#EEF6F0, #f5f5f5);
			position: fixed;

			image {
				width: 100%;
				height: 500rpx;
			}
		}

		.sign_img {
			width: 230rpx;
			height: 120rpx;
		}

		.pay-type-icon {
			width: 36rpx;
			height: 36rpx;
			border-radius: 36rpx;
			line-height: 36rpx;
		}

		.abnormal-order-info {
			height: 59rpx;
			color: #FF3333;
			background: #FFEAEA;
			border-radius: 4rpx;
			padding: 0 10rpx 0 30rpx;

			.icon-right {
				font-size: 24rpx;
				transform: scale(0.8);
			}
		}

		.item-child {
			.avatar {
				width: 140rpx;
				height: 140rpx;
			}
		}

		.oper-btn {
			width: 174rpx;
			height: 72rpx;
			border-radius: 36rpx;
			border: 1rpx solid #999;
			margin-left: 20rpx;
		}

		.oper-btn.sm {
			width: 124rpx;
		}

		.oper-btn:nth-child(1) {
			margin-left: 0;
		}

		.order-type-box {
			width: 690rpx;
			border-radius: 16rpx;
		}
	}
</style>